﻿using System;
using System.Windows.Input;

namespace SQLDeployAnything.Data.Commands
{
    public class CreateConnection : ICommand
    {
        private Environment.Environment _Env;
        internal CreateConnection(Environment.Environment currentEnvironment)
        {
            _Env = currentEnvironment;
        }

        public bool CanExecute(object parameter)
        {
            if (_Env == null)
                return false;
            
            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            if (_Env != null)
            {
                WPFHelper.Dialog2.DialogWindow Dialog = new WPFHelper.Dialog2.DialogWindow();
                UI.NewConnectionPrompt.ConnectionTypeSelector selector = new UI.NewConnectionPrompt.ConnectionTypeSelector();
                Dialog.DataContext = selector;
                bool? result = Dialog.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    object item = selector.cmb_SelectedType.SelectedItem;
                    if (item != null && item is Type)
                    {
                        Type newConnectionType = (Type)item;
                        var newConnection = Activator.CreateInstance(newConnectionType);
                        _Env.Connections.Add((SQLDeployAnything.Data.Environment.Connection)newConnection);
                    }
                }
            }   
        }
    }
}
